package com.garbagecode.util.pagination.dialect;

import org.apache.ibatis.session.RowBounds;

/**
 * 
 * @author cc.z
 *
 */
public class MySqlDialect implements Dialect {

	@Override
	public String getBoundSql(String originSql, int offset, int limit, String order) {
		if (originSql == null) {
			throw new IllegalArgumentException("parameter 'originSql' is null");
		}
		
		StringBuffer newSqlBuf = new StringBuffer(originSql);

		if (order != null && order.trim().length() > 0) {
			newSqlBuf.append(" ORDER BY ").append(order.replaceAll("\\.", " "));
		}

		if (offset != RowBounds.NO_ROW_OFFSET) {
			newSqlBuf.append(" LIMIT ").append(offset);

			if (limit != RowBounds.NO_ROW_LIMIT) {
				newSqlBuf.append(",").append(limit);
			} else {
				newSqlBuf.append(",").append(Long.MAX_VALUE);
			}
		} else if (limit != RowBounds.NO_ROW_LIMIT) {
			newSqlBuf.append(" LIMIT 0,").append(limit);
		}

		return newSqlBuf.toString();
	}

	@Override
	public String getTotalSql(String originSql) {
		if (originSql == null) {
			throw new IllegalArgumentException("parameter 'originSql' is null");
		}
		
		int fromPos = originSql.toLowerCase().indexOf(" from ");
		
		if (fromPos < 0) {
			throw new RuntimeException("not found key 'from' in sql '" + originSql + "'");
		}
		
		String newSql = "SELECT COUNT(*) FROM " + originSql.substring(fromPos + 6);
		
		return newSql;
	}

}
